const { createDirectus, rest, authentication, readItems, createItem, createItems, staticToken} = require('@directus/sdk');
require('dotenv').config();

class DirectusClient {
  constructor() {
    this.client = createDirectus('http://1.117.204.28:8055')
      .with(rest())
      // .with(authentication('static', { token: process.env.DIRECTUS_TOKEN }));
      .with(staticToken('3wgee-71Su-z1_l042Sj61uFuqYJ-MDk'))
  }

  async getClient() {
    return this.client;
  }

  // 获取商品列表
  async getProducts() {
    try {
      const products = await this.client.request(
        readItems('goods', {
          fields: ['*']
        })
      );
      console.log(`成功从 ${'goods'} 获取商品数据`);
      return products;
    } catch (error) {
      console.log(`尝试 ${'goods'} 失败:`, error.errors?.[0]?.message || error.message);
    }
  }

  // 获取订单生成配置
  async getOrderSettings() {
    try {
      const settings = await this.client.request(
        readItems('config', {
          fields: ['*']
        })
      );
      console.log(`成功从 ${'config'} 获取配置数据`);
      return settings;
    } catch (error) {
      console.log(`尝试 ${'config'} 失败:`, error.errors?.[0]?.message || error.message);
    }
  }


  // 批量创建订单
  async createOrders(ordersData) {
    try {
      const orders = await this.client.request(
        createItems('order', ordersData)
      );
      console.log(`成功在 ${'order'} 批量创建订单`);
      return orders;
    } catch (error) {
      console.log(`尝试在 ${'order'} 批量创建订单失败:`, error.errors?.[0]?.message || error.message);
    }
  }
}

module.exports = DirectusClient;
